import type { RouteRecordRaw } from 'vue-router';
import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
// import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
import { staticRoutes, allAsyncRoutes, anyRoute } from '@/router/routes'
import userinfoApi, { type userinfoModel } from '@/api/userinfo';
import router from "@/router";
import { cloneDeep } from 'lodash'

// 筛选路由
const filterRoutesHandler = (routes: RouteRecordRaw[], routesName: string[]) => {
  let result = routes.filter(route => {
    if (route.children) {
      route.children = filterRoutesHandler(route.children, routesName);
    }
    return routesName.includes(route.name as string);
  })
  return result;
}

// 动态注册路由
const addRoutes = (allRoutes: RouteRecordRaw[]) => {
  allRoutes.forEach(route => {
    router.addRoute(route); // 这个方法是 router.addRoute() 是vue-router提供的,目的就是为了动态注册路由
  })
}

interface UserInfoState {
  token: string,
  userinfo: userinfoModel,
  menuRoutes: RouteRecordRaw[]
}

const initUserinfo = (): userinfoModel => ({
  avatar: '',
  name: '',
  buttons: [],
  roles: [],
  routes: []
})

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    userinfo: initUserinfo(),
    menuRoutes: []
  }),

  actions: {
    async login(username: string, password: string) {
      try {
        let result = await userinfoApi.login({ username, password })
        // 存到store中
        console.log(result);

        this.token = result.token
        // 存到localStorage
        setToken(result.token)
      } catch (error) {
        ElMessage.error('登录失败，请重试')
        return Promise.reject(error)
      }
    },
    async getInfo() {
      try {
        let result = await userinfoApi.info()
        console.log('获取到的个人信息', result);
        this.userinfo = result;
        // this.menuRoutes = staticRoutes
        const filterRoutes = filterRoutesHandler(cloneDeep(allAsyncRoutes), result.routes);
        const allRoutes = staticRoutes.concat(filterRoutes, anyRoute);
        this.menuRoutes = allRoutes;
        addRoutes(allRoutes); // 动态注册路由
      } catch (error) {
        ElMessage.error('获取个人用户信息失败,请重试')
        return Promise.reject(error);
      }
    },
    async logout() {
      try {
        let result = await userinfoApi.logout();
        this.reset()
      } catch (error) {
        ElMessage.error('退出登录失败,请重试')
        return Promise.reject(error);
      }
    },

    reset() {
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.userinfo = initUserinfo()
    },
  },
});
